package com.kkwrite.regimen.provider.service.share;

import com.kkwrite.regimen.common.constant.DeletedEnum;
import com.kkwrite.regimen.common.entity.dto.InDTO;
import com.kkwrite.regimen.provider.domain.RegShareLogDO;
import com.kkwrite.regimen.provider.domain.RegShopShareLogDO;
import com.kkwrite.regimen.provider.exception.ServiceException;
import com.kkwrite.regimen.provider.repository.RegShareLogRepository;
import com.kkwrite.regimen.provider.repository.RegShopShareLogRepository;
import com.kkwrite.regimen.provider.stream.dto.RewardPointDTO;
import com.kkwrite.regimen.provider.stream.service.RewardPointService;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by lisha on 2018/7/19 21:30.
 *
 * @author lisha
 */
@Service(value = "shareService")
public class ShareServiceImpl implements ShareService {

    @Resource(name = "regShareLogRepository")
    private RegShareLogRepository repository;
    @Resource(name = "regShopShareLogRepository")
    private RegShopShareLogRepository shopShareLogRepository;
    @Resource
    private RewardPointService rewardPointService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLog(InDTO<Map<String, String>> inDTO) {
        RegShareLogDO logDO = new RegShareLogDO();
        Map<String, String> param = inDTO.getBody();
        int userId = Integer.valueOf(param.get("userId"));
        logDO.setUserId(userId);
        short type = Short.valueOf(param.get("type"));
        logDO.setType(type);
        logDO.setDeleted(DeletedEnum.UN_DELETED.getValue());
        String itemIdString = param.get("itemId");
        if (!"-999".equals(itemIdString)) {
            logDO.setItemId(Integer.valueOf(itemIdString));
        }
        repository.save(logDO);
        switch (type) {
            // 加积分  1-邀请好友 2-分享项目详情 3-分享首页
            case 1:
                if (!rewardPointService.send(new RewardPointDTO(userId, 50, "当天首次分享邀请码", type, itemIdString))) {
                    throw new ServiceException("消息发送失败");
                }
                break;
            case 2:
                if (!rewardPointService.send(new RewardPointDTO(userId, 50, "当天首次分享项目", type, itemIdString))) {
                    throw new ServiceException("消息发送失败");
                }
                break;
            case 3:
                if (!rewardPointService.send(new RewardPointDTO(userId, 50, "当天首次分享首页", type, itemIdString))) {
                    throw new ServiceException("消息发送失败");
                }
                break;
            default:
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveShopShareLog(Integer shopId, Integer empId, Integer type, Integer itemId) {
        RegShopShareLogDO log = new RegShopShareLogDO();
        log.setShopId(shopId);
        log.setEmployeeId(empId);
        log.setType(type);
        log.setArticleId(itemId);
        log.setDeleted(DeletedEnum.UN_DELETED.getValue());
        shopShareLogRepository.saveAndFlush(log);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = true)
    public boolean isFirstShare(int userId, short type, String itemId) {
        // 判断是否是当天第一次分享
        Timestamp beginTime = Timestamp.valueOf(LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0, 0)));
        Timestamp endTime = Timestamp.valueOf(LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59)));
        Specification<RegShareLogDO> querySpecification = (root, query, cb) -> {
            List<Predicate> predicates = new LinkedList<>();
            predicates.add(cb.lessThanOrEqualTo(root.get("gmtCreate").as(Timestamp.class), endTime));
            predicates.add(cb.greaterThanOrEqualTo(root.get("gmtCreate").as(Timestamp.class), beginTime));
            predicates.add(cb.equal(root.get("userId").as(Integer.class), userId));
            predicates.add(cb.equal(root.get("type").as(Short.class), type));
            if (type == 2) {
                predicates.add(cb.equal(root.get("itemId").as(Integer.class), Integer.valueOf(itemId)));
            }
            return query.where(predicates.toArray(new Predicate[0])).getRestriction();
        };
        List<RegShareLogDO> list = repository.findAll(querySpecification);
        return list.size() == 1;
    }

}
